let emojiPanelVisible = false;
let textInput;

document.addEventListener('DOMContentLoaded', function() {
    if (IS_LOGGED_IN) {
        textInput = document.getElementById('contentInput');
        
        // 表单提交
        const postForm = document.getElementById('postForm');
        if (postForm) {
            postForm.addEventListener('submit', function(e) {
                e.preventDefault();
                postShuoshuo();
            });
        }
    }
    
    // 格式化时间显示
    formatTimes();
    
    // 加载评论
    loadAllComments();
});

function showPostPanel() {
    const panel = document.getElementById('postPanel');
    panel.style.display = 'block';
    panel.scrollIntoView({ behavior: 'smooth', block: 'start' });
    if (textInput) {
        textInput.focus();
    }
}

function hidePostPanel() {
    const panel = document.getElementById('postPanel');
    panel.style.display = 'none';
    if (textInput) {
        document.getElementById('contentInput').value = '';
    }
    emojiPanelVisible = false;
    const emojiPanel = document.getElementById('emojiPanel');
    if (emojiPanel) {
        emojiPanel.style.display = 'none';
    }
}

function formatTimes() {
    const timeElements = document.querySelectorAll('.shuoshuo-time[data-time]');
    timeElements.forEach(function(element) {
        const timestamp = parseInt(element.getAttribute('data-time'));
        const timeStr = formatTime(timestamp);
        element.textContent = timeStr;
    });
}

function formatTime(timestamp) {
    const now = Math.floor(Date.now() / 1000);
    const diff = now - timestamp;
    
    if (diff < 60) {
        return diff + '秒前';
    } else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前';
    } else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前';
    } else if (diff < 604800) {
        return Math.floor(diff / 86400) + '天前';
    } else {
        const date = new Date(timestamp * 1000);
        return date.getFullYear() + '-' + 
               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
               String(date.getDate()).padStart(2, '0') + ' ' +
               String(date.getHours()).padStart(2, '0') + ':' + 
               String(date.getMinutes()).padStart(2, '0');
    }
}

function toggleEmoji() {
    const panel = document.getElementById('emojiPanel');
    emojiPanelVisible = !emojiPanelVisible;
    panel.style.display = emojiPanelVisible ? 'flex' : 'none';
}

function insertEmoji(emoji) {
    if (!textInput) return;
    
    const start = textInput.selectionStart;
    const end = textInput.selectionEnd;
    const text = textInput.value;
    const newText = text.substring(0, start) + emoji + text.substring(end);
    
    textInput.value = newText;
    textInput.focus();
    textInput.setSelectionRange(start + emoji.length, start + emoji.length);
}

function postShuoshuo() {
    if (!textInput) return;
    const content = textInput.value.trim();
    
    if (!content) {
        alert('内容不能为空');
        return;
    }

    fetch('/api/post', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'content=' + encodeURIComponent(content)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            alert('发布成功！');
            hidePostPanel();
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发布失败，请稍后重试');
    });
}

function deleteShuoshuo(id) {
    if (!confirm('确定要删除这条说说吗？')) {
        return;
    }

    fetch('/api/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + id
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            alert('删除成功！');
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除失败，请稍后重试');
    });
}

function toggleComment(shuoshuoID) {
    const inputArea = document.getElementById(`comment-input-${shuoshuoID}`);
    if (inputArea) {
        if (inputArea.style.display === 'none') {
            inputArea.style.display = 'block';
            
            // 加载评论（只加载一次）
            if (!commentPages[shuoshuoID]) {
                loadComments(shuoshuoID);
            }
            
            // 聚焦到输入框
            const textarea = inputArea.querySelector('.comment-input');
            if (textarea) {
                setTimeout(() => textarea.focus(), 100);
            }
        } else {
            inputArea.style.display = 'none';
        }
    }
}

function cancelComment(shuoshuoID) {
    const inputArea = document.getElementById(`comment-input-${shuoshuoID}`);
    if (inputArea) {
        const textarea = inputArea.querySelector('.comment-input');
        if (textarea) {
            textarea.value = '';
        }
        inputArea.style.display = 'none';
    }
}

function postComment(shuoshuoID) {
    const item = document.querySelector(`[data-id="${shuoshuoID}"]`);
    const textarea = item.querySelector('.comment-input');
    const content = textarea.value.trim();
    
    if (!content) {
        alert('评论内容不能为空');
        return;
    }

    fetch('/api/comment', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'shuoshuo_id=' + shuoshuoID + '&content=' + encodeURIComponent(content)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            textarea.value = '';
            
            // 重置页码，重新加载第一页评论
            commentPages[shuoshuoID] = 1;
            loadComments(shuoshuoID);
            
            // 隐藏输入框
            const inputArea = document.getElementById(`comment-input-${shuoshuoID}`);
            if (inputArea) {
                inputArea.style.display = 'none';
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发表评论失败');
    });
}

// 存储每个说说的评论页码
const commentPages = {};

function loadAllComments() {
    // 允许所有用户（包括未登录）查看评论
    // 默认不自动加载评论，由用户点击"评论"按钮后再加载
}

function loadComments(shuoshuoID, page = 1) {
    if (!commentPages[shuoshuoID]) {
        commentPages[shuoshuoID] = 1;
    }
    
    const currentPage = commentPages[shuoshuoID];
    
    fetch('/api/comments?shuoshuo_id=' + shuoshuoID + '&page=' + currentPage)
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error(data.error);
            return;
        }

        const container = document.getElementById('comments-' + shuoshuoID);
        if (!container) return;

        if (data.comments && data.comments.length > 0) {
            let html = '';
            
            // 如果是第一页，显示标题
            if (currentPage === 1) {
                html = '<h4>评论 (' + data.total + ')</h4>';
            }
            
            // 只渲染新加载的评论（追加模式）
            data.comments.forEach(function(comment) {
                const time = formatTime(comment.created_at);
                html += `
                    <div class="comment-item">
                        <div class="comment-author">@${comment.nickname}</div>
                        <div class="comment-content">${comment.content}</div>
                        <div class="comment-time">${time}</div>
                    </div>
                `;
            });
            
            // 追加到现有内容
            if (currentPage === 1) {
                container.innerHTML = html;
            } else {
                container.innerHTML += html;
            }
            
            // 如果有更多评论，显示"更多"按钮
            if (data.has_more) {
                container.innerHTML += `
                    <button class="more-comments-btn" onclick="loadMoreComments(${shuoshuoID})">
                        查看更多评论
                    </button>
                `;
            }
        } else if (currentPage === 1) {
            // 第一页且没有评论
            container.innerHTML = '';
        }
    })
    .catch(error => {
        console.error('Error loading comments:', error);
    });
}

function loadMoreComments(shuoshuoID) {
    commentPages[shuoshuoID] = (commentPages[shuoshuoID] || 1) + 1;
    loadComments(shuoshuoID, commentPages[shuoshuoID]);
}
